package com.foreveross.proxyip.core.zk.task.strategy;

import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayatang.domain.InstanceFactory;
import com.foreveross.proxyip.core.BaseCode;
import com.foreveross.proxyip.core.pools.AvailablePool;
import com.foreveross.proxyip.core.pools.thread.CheckOutValidateThread;
import com.foreveross.proxyip.core.zk.task.ZkTask;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;
import com.foreveross.proxyip.util.ThreadUtils;

public class CheckOutTask extends ZkTask {
	protected static final Logger log =  LoggerFactory.getLogger(CheckOutTask.class);
	@Override
	public boolean breakTask(String taskParams) throws Exception {
		//只要有任务就检出验证
		return false;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public int exec(Long[] taskNum, String taskParams) throws Exception {
		Long threadTimeout = Long.parseLong(BaseCode.getValue("THREAD_EXECUTE_TIMEOUT"));
		AvailablePool pool = this.getPool(taskParams);
		Constructor constructor = null;
		try {
			IBaseRepository repository = InstanceFactory.getInstance(IBaseRepository.class,"channelEntityRepository");
			
			if(taskNum==null||taskNum.length==0){
				return  -1;
			}
			
			List iplist = pool.poolIpMap.getKeys(taskNum[0],taskNum[1]);
			
			if(iplist==null||iplist.size()==0){
				return 1;
			}

			constructor = CheckOutValidateThread.class.getConstructor(List.class,AvailablePool.class,IBaseRepository.class);
			ThreadUtils.openThreads(constructor, iplist, pool.threadMaxIpCount,threadTimeout,pool, repository);
		} catch (Exception e) {
			log.error(pool.poolName + "检出异常, 现池中ip数： " +  pool.poolIpMap.size() + ", 范围区间：" + Arrays.toString(taskNum) ,e);
		} 
		
		return 1;
	}

}
